package cn.tedu.csmall.stock.webapi.controller;

import cn.tedu.csmall.commons.pojo.stock.dto.StockReduceCountDTO;
import cn.tedu.csmall.commons.restful.JsonResult;
import cn.tedu.csmall.stock.service.IStockService;
import cn.tedu.csmall.stock.webapi.exception.BlockError;
import cn.tedu.csmall.stock.webapi.exception.Fallback;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Api(tags = "库存模块")
@RequestMapping("/base/stock")
public class StockController {
    @Autowired
    private IStockService stockService;


    @PostMapping("/reduce/count")
    @ApiOperation("减少商品库存")
    //@SentinelResource注解描述的方法，就交给了sentinel进行管理
    //这个方法的应用资源名是指定的stock
    @SentinelResource(value = "stock",
            blockHandlerClass = BlockError.class,blockHandler = "block",
            fallbackClass = Fallback.class,fallback = "fallbackError")
    public JsonResult reduceCommodityCount(StockReduceCountDTO stockReduceCountDTO){
        //80%的概率，抛出异常(模拟)
        if (Math.random()<0.8)
            System.out.println(1/0);
        stockService.reduceStockByCommodityCode(stockReduceCountDTO);
        return JsonResult.ok("减少商品库存完成！");
    }
}
